/*
 *   C++ sockets on Unix and Windows
 *   Copyright (C) 2002
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "PracticalSocket.h"  // For Socket, ServerSocket, and SocketException
#include <iostream>           // For cout, cerr
#include <sstream>           // For cout, cerr
#include <cstdlib>            // For atoi()  
#include <pthread.h>          // For POSIX threads  
#include <string.h>            // For strerror

const int RCVBUFSIZE = 32;
const int SNDBUFSIZE = 32;
const int CLIENTBUFSIZE = 32;

int D=1;

void HandleTCPClient(TCPSocket *sock);     // TCP client handling function
void *ThreadMain(void *arg);               // Main program of a thread  

// Variables used to track the clients this server knows about
int numClients;
int* ClientId;
string* ClientIp;
string* ClientPort;


int main(int argc, char *argv[]) {
  stringstream ss;
  if (argc != 2) {                 // Test for correct number of arguments  
    cerr << "Usage: " << argv[0] << " <Server Port> " << endl;
    exit(1);
  }

  // Initialize buffer for clients this server is aware of
  ClientId = new int[CLIENTBUFSIZE];
  ClientIp = new string[CLIENTBUFSIZE];
  ClientPort = new string[CLIENTBUFSIZE];
  numClients = 0;

  unsigned short echoServPort = atoi(argv[1]);    // First arg:  local port  

  try {
    TCPServerSocket servSock(echoServPort);   // Socket descriptor for server  
  
    for (;;) {      // Run forever  
      // Create separate memory for client argument  
      TCPSocket *clntSock = servSock.accept();



      char recvBuffer[RCVBUFSIZE];
      int recvMsgSize;
      recvMsgSize = clntSock->recv(recvBuffer, RCVBUFSIZE);
      if(recvMsgSize < 0)
      {
        cout << "Unable to receive initial message" << endl;
        exit(1);
      }
      else
      {
        ClientId[numClients] = atoi(recvBuffer);
      }
      // Add client to database
      int inDatabase = -1;
      for(int i=0; i<numClients; i++)
      {
        if(ClientId[numClients] == ClientId[i])
        {
          if(D==1) cout << "This client is already in the database" << endl;
          inDatabase = i;
          break;
        }

      }

      ss.flush();
      ss.clear();
      if(D==1)
      {
        cout << "NumClients " << numClients << endl;
        cout << "inDatabase " << inDatabase << endl;
      }

      if(inDatabase==-1)
      {
        inDatabase=numClients;
        ClientIp[numClients] = clntSock->getForeignAddress();
        ss << clntSock->getForeignPort();
        ss >> ClientPort[numClients]; 
        numClients++;
      }
      else
      {
        ClientIp[inDatabase] = clntSock->getForeignAddress();
        ss << clntSock->getForeignPort();
        ss >> ClientPort[inDatabase]; 
      }
      ss.flush();
      ss.clear();

      cout << "NumClients " << numClients << endl;

      cout << "Hello Client ID " << ClientId[inDatabase] << " " << ClientIp[inDatabase] << ":" << ClientPort[inDatabase] << endl;
  
      // Create client thread  
      pthread_t threadID;              // Thread ID from pthread_create()  
      if (pthread_create(&threadID, NULL, ThreadMain, 
              (void *) clntSock) != 0) {
        cerr << "Unable to create thread" << endl;
        exit(1);
      }
    }
  } catch (SocketException &e) {
    cerr << e.what() << endl;
    exit(1);
  }
  // NOT REACHED

  return 0;
}

// TCP client handling function
void HandleTCPClient(TCPSocket *sock) {
  int idReq = 1;
  // Tell client we are ready
  sock->send("r", 1);

  while(idReq!=-1)
  {
    // Wait for instructions from client
    char echoBuffer[RCVBUFSIZE];
    int recvMsgSize;
    int bytesReceived=0;
    if ((bytesReceived = (sock->recv(echoBuffer, RCVBUFSIZE))) <= 0) {
      cerr << "Unable to read";
      exit(1);
    }
    echoBuffer[bytesReceived] = '\0';          // Terminate the string!

    idReq = atoi(echoBuffer);
    int inDatabase=-1;

    cout << "Id recvd " << idReq << endl;

    if(idReq==-1)
      break;

    // Check if the server knows about the received client id
    for(int i=0; i<numClients; i++)
    {
      if(ClientId[i] == idReq)
      {
        inDatabase = i;
        break;
      }
    }
    if(inDatabase==-1)
      sock->send("o", 1);
    else
    {
      sock->send("i", 1);
      cout << "Sending " << ClientIp[inDatabase].c_str() << endl;
      cout << "Sending " << ClientPort[inDatabase].c_str() << endl;
      sock->send(ClientIp[inDatabase].c_str(), ClientIp[inDatabase].length());
      //sock->send(ClientPort[inDatabase].c_str(), ClientPort[inDatabase].length());
    }
  }
  cout << "Leaving" << endl;
}

void *ThreadMain(void *clntSock) {
  // Guarantees that thread resources are deallocated upon return  
  pthread_detach(pthread_self()); 

  // Extract socket file descriptor from argument  
  HandleTCPClient((TCPSocket *) clntSock);

  delete (TCPSocket *) clntSock;
  return NULL;
}

